package com.example.kotlinandroidstudy.api

import android.util.Log
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit


class RetrofitClient<T> {
    //    companion object {
//        val instance: RetrofitClient by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { RetrofitClient() }
//    }
//请求超时时间5S
    private val connectionTimeoutTime = 60L
    private val httpLoggingInterceptor = HttpLoggingInterceptor().setLevel(
        HttpLoggingInterceptor.Level.BODY
    )
    private val okhttpBuilder: OkHttpClient =
        OkHttpClient.Builder()
            .addNetworkInterceptor(httpLoggingInterceptor)
            .addInterceptor(LogInterceptor())
            .connectTimeout(connectionTimeoutTime, TimeUnit.SECONDS)//链接超时设置
            .readTimeout(connectionTimeoutTime, TimeUnit.SECONDS)//读取超时时间设置
            .writeTimeout(connectionTimeoutTime, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)//默认重试一次 若需要重试N次则要实现拦截器
            .build()


    //日志拦截
    class LogInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            var request = chain.request()
            Log.i(
                "okhttp:",
                " Requeste " + "\nmethod:" + request.method() + "\nurl:" + request.url() + "\nbody:" + request.body()
                    .toString()
            )
            var response = chain.proceed(request)
            Log.i(
                "wxf",
                " Response " + "\nsuccessful:" + response.isSuccessful + "\nbody:" + response.peekBody(
                    1024
                )?.string()
            )
            return response
        }
    }

    fun getService(cls: Class<T>): T? {
        return Retrofit.Builder()
            .client(okhttpBuilder)
            .baseUrl("https://httpbin.org/")
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build().create(cls)

    }
}